package belf.migrate.plugin.oracle.listener;

import belf.migrate.plugin.oracle.antlr.PlSqlLexer;
import belf.migrate.plugin.oracle.antlr.PlSqlParser;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.gui.TreeViewer;

import javax.swing.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * 解析Oracle SQL语句，以Tree的方式展示
 */
public class OracleSqlTree {
    public static void main(String[] args) throws Exception {
        String sql = String.join("\n", Files.readAllLines(Paths.get(args[0])));
        long begin = System.currentTimeMillis();
        // 读取输入SQL语句

        // 创建一个CharStream
        CharStream input = CharStreams.fromString(sql);

        // 使用MySqlLexer进行词法分析
        PlSqlLexer lexer = new PlSqlLexer(input);

        // 使用CommonTokenStream将词法分析器生成的词汇流传递给解析器
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // 使用MySqlParser进行语法分析
        PlSqlParser parser = new PlSqlParser(tokens);

        // 从解析器中获取起始规则并进行解析
        ParseTree tree = parser.sql_script();

        long end = System.currentTimeMillis();

        // 打印解析树
        System.out.println(tree.toStringTree(parser));
        System.out.println("spends: " + (end - begin));

        // 使用TreeViewer展示解析树
        JFrame frame = new JFrame("Oracle Parse Tree");
        JPanel panel = new JPanel();
        TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree);
        viewer.setScale(1.5); // 缩放树的大小
        panel.add(viewer);
        frame.add(new JScrollPane(panel));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }
}
